﻿package data
{
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.system.LoaderContext;
	import flash.system.Security;
	
	/*
	 * Класс с серверными запросами
	 */
	public class Servant
	{
		private var loader:URLLoader;
		private var calback:Function;
		public function Servant():void
		{
		
		}
		
		// получаем название песни
		public function getSong(url:String):void
		{
			Security.allowDomain("*");
			Security.allowInsecureDomain("*");
			Security.allowDomain("www.google.com");
			
			loader = new URLLoader();
			loader.addEventListener(Event.COMPLETE, onLoaderComlete);
			loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurError);
			
			var lc:LoaderContext = new LoaderContext();
			lc.checkPolicyFile = false;
			
			var _request:URLRequest = new URLRequest(url);
			loader.load(_request);
		}
		
		private function addUrlRnd():String
		{
			return "djdj=" + (new Date()).getMilliseconds();
		}
		
		private function onLoaderComlete(event:Event = null):void
		{
			if (loader.data != null)
			{
				calback(loader.data);
			}
		}
		
		private function onIOError(event:IOErrorEvent):void
		{
			trace("IO_ERROR > " + event);
		}
		
		private function onSecurError(event:SecurityErrorEvent):void
		{
			trace("SECURITY_ERROR > " + event);
		}
		
		public function destroy():void
		{
			loader.removeEventListener(Event.COMPLETE, onLoaderComlete);
			loader.removeEventListener(IOErrorEvent.IO_ERROR, onIOError);
			loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurError);
			loader = null;
			calback = null;
		}
		
		public function set onComplete(cb:Function):void
		{
			calback = cb;
		}
	}
}
